//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.app.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Component
public class JWTUtil {
    /**
     * 100天的expiration time
     */
    private static final long EXPIRATION_TIME = 100 * 24 * 60 * 60 * 1000L;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    public JWTUtil() {
    }

    public static boolean verify(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    public static String getUsername(String token) {
        try {
            try {
                DecodedJWT jwt = JWT.decode(token);
                return jwt.getClaim("username").asString();
            } catch (Exception var2) {
                var2.printStackTrace();
                return null;
            }
        } catch (JWTDecodeException var3) {
            return null;
        }
    }

    public static String random() {
        Integer code = (int)((Math.random() * 9.0D + 1.0D) * 100000.0D);
        return code + "";
    }

    public String sign(String username, String secret) throws UnsupportedEncodingException {
        Date date = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        Algorithm algorithm = Algorithm.HMAC512(secret);

        String token = Jwts.builder().claim("username", username).setExpiration(date).signWith(SignatureAlgorithm.HS512, secret).compact();

//        return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
        return token;
    }
}
